package com.borened.netty.protocol.mqtt;

import com.borened.netty.util.ByteBufUtil;
import com.borened.netty.util.SpringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttMessageBuilders;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author chengcaihua
 * @description
 * @since 2023-11-13 17:00
 */
@Data
@AllArgsConstructor
public class Subscriber {

    private String topic;

    private MqttClientSession mqttClientSession;


    /**
     * 接收消息
     * @param persistentMessage 其他客户端发送的消息
     */
    public void receiveMessage(MqttPersistentMessage persistentMessage) {
        if (mqttClientSession.getChannel() == null || !mqttClientSession.getChannel().isActive()) {
            return;
        }
        //接收消息
        MqttPublishMessage pushSubscribeMessage = MqttMessageBuilders.publish()
                .messageId(new Random().nextInt(2^32))
                .topicName(topic)
                .payload(ByteBufUtil.allocator(persistentMessage.getPayload()))
                .qos(persistentMessage.getQos())
                .retained(persistentMessage.isRetain())
                .build();
        mqttClientSession.getChannel().writeAndFlush(pushSubscribeMessage);
    }
}
